package com.prd.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.prd.config.OssConfig;
import com.prd.service.FileService;
import com.prd.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author lizhaoyi
 * @date 2023/10/4 15:15
 * Description:
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OssConfig ossConfig;

    @Override
    public String uploadImg(MultipartFile file) {
        //获取相关配置
        String bucketname = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();

        //JDK8的日期格式
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //拼装路径，oss上存储的路径 user/2023/02/14/xxxx.jpg
        String folder = dtf.format(ldt);
        String fileName = CommonUtil.generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在oss上bucket创建user文件夹
        String newFileName = "oa/"+folder+"/"+fileName+extension;

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketname, newFileName, file.getInputStream());
            //返回路径
            if (putObjectResult != null) {
                return "http://"+bucketname+"."+endpoint+"/"+newFileName;
            }

        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
        }finally {
            //oss关闭服务，否则会造成OOM
            ossClient.shutdown();
        }


        return null;
    }

}
